// 引入axios以及element ui中的loading和message组件
import axios from "axios";
import { message } from "ant-design-vue";
import crypto from "@/tool/crypto";
// import localStorageEx from "localstorageex";
import router from "@/router";
import store from "@/store";
// http请求拦截器,请求时
// axios.defaults.timeout = 30000;
// 带cookie请求
axios.defaults.withCredentials = true;
axios.interceptors.request.use(
  config => {
    // 请求时的处理
    let token = localStorage.getItem("token");
    if (token) {
      token = crypto.getAES(token);
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      if (router.history.current.name !== "login") {
        config.headers.token = token;
      }
    }
    return config;
  },
  error => {
    // 异常时的处理
    message.error({
      message: "加载超时"
    });
    return Promise.reject(error);
  }
);

// http响应拦截器，请求后,必须先关闭loading
axios.interceptors.response.use(
  data => {
    //  请求后成功的处理
    // 响应成功
    store.dispatch("changeSpinning", false);
    if (data.data != null && typeof data.data === "object") {
      if (data.data.success && data.data.data.status === 200) {
        return data.data.data.data;
      } else {
        if (!data.data.success) {
          return Promise.reject(data.data.message);
        } else {
          if (data.data.data.status === 201) {
            router.replace("/admin/login");
            return Promise.reject(data.data.data.msg);
          } else {
            return Promise.reject(data.data.data.msg);
          }
        }
      }
    }
  },
  error => {
    // 请求后异常的处理
    store.dispatch("changeSpinning", false);
    let errMsg = "";
    if (error.response) {
      switch (error.response.status) {
        case 400:
          errMsg = "请求错误";
          break;

        case 401:
          errMsg = "未授权，请登录";
          router.replace({
            path: "/"
          });
          break;

        case 403:
          errMsg = "拒绝访问";
          break;

        case 404:
          errMsg = `请求地址出错: ${error.response.config.url}`;
          break;

        case 408:
          errMsg = "请求超时";
          break;

        case 500:
          errMsg = "服务器内部发生错误";
          break;

        case 501:
          errMsg = "服务未实现";
          break;

        case 502:
          errMsg = "网关错误";
          break;

        case 503:
          errMsg = "服务不可用";
          break;

        case 504:
          errMsg = "网关超时";
          break;

        case 505:
          errMsg = "HTTP版本不受支持";
          break;
        default:
      }
    } else {
      errMsg = "Network Error";
    }
    return Promise.reject(errMsg);
  }
);
export default {
  post(url, data) {
    store.dispatch("changeSpinning", true);
    return axios.post(url, data);
  },
  // get方法
  get(url, data) {
    store.dispatch("changeSpinning", true);
    return axios.get(url, { params: data });
  }
};
